package com.portal.notification;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;

/**
 * Execute command.
 * @author xe33636
 */
public class Program {
	private int exitCode = -1;

	private void setExitCode(int exitCode) {
		this.exitCode = exitCode;
	}

	public int getExitCode() {
		return this.exitCode;
	}

	public String run(String[] args) {
		return runProgram(args);
	}

	private String runProgram(String[] args) {
		String line = "";
		String out = "";
		String path = System.getProperty("java.io.tmpdir");
		String osLineSep = System.getProperty("line.separator");
		Process process = null;
		try {
			process = new ProcessBuilder(args).directory(new File(path))
					.start();

			InputStream is = process.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			StringBuilder sb = new StringBuilder();
			while ((line = br.readLine()) != null) {
				sb.append(new StringBuilder().append(line).append(osLineSep)
						.toString());
			}
			br.close();
			process.waitFor();
			out = sb.toString();
			int eCode = process.exitValue();
			if (eCode == 0) {
				System.out.println(new StringBuilder()
				.append("Successfully launched command \"")
				.append(Arrays.toString(args)).append("\"").toString());
			} else {
				System.out.println(new StringBuilder().append("running ")
						.append(Arrays.toString(args))
						.append(" raised errorcode ").append(eCode).toString());
				System.err.println(new StringBuilder().append("running ")
						.append(Arrays.toString(args))
						.append(" raised errorcode ").append(eCode).toString());
			}
			setExitCode(eCode);
		} catch (IOException e) {
			String error = e.getLocalizedMessage();
			System.out.println(new StringBuilder().append("Attempting to run \"")
					.append(Arrays.toString(args)).append("\" has failed:")
					.toString());
			System.out.println(error);
			System.err.println(error);
			System.err.println(Arrays.toString(args));
			setExitCode(420);
			return error;
		} catch (Exception e) {
			String error = e.getLocalizedMessage();
			System.out.println(new StringBuilder().append("Attempting to run \"")
					.append(Arrays.toString(args)).append("\" has failed:")
					.toString());
			System.out.println(error);
			System.err.println(error);
			System.err.println(Arrays.toString(args));
		}
		return out;
	}
}
